#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include "Options.h"
#include "Common.h"
#include "Log.h"
#include "mm_framework.h"


Log *g_pLog;
Option option;

int main(int argc,char* argv[])
{
	if (argc < 2)
	{
		printf ("usage: Exchange config_file [option]\n");
		return -1;
	}

	char ini_file[256] = {0};
	strncpy (ini_file ,argv[1], sizeof (ini_file));

	if(access (ini_file, F_OK) != 0)
	{
		printf("get config file:%s error\n", ini_file);
		return -1;
	}
	
	if(option.init (ini_file) != 0)
	{
		printf ("initalize config file:%s error\n", ini_file);
		return -1;
	}

	g_pLog = new Log (ini.log_dir, ini.log_priority, ini.log_size, ini.log_num, ini.log_prename);
	printf ("initalize log \t\t\t[ok]\n");
	
	init_fdlimit ();

	daemon_start ();
	
	pid_t pid;
	if ( (pid = fork ()) < 0)
	{
		printf ("fork error\n");
		return -1;
	}
	else if (pid == 0) 
	{
		mm_framework worker;
		if(worker.Init() == 0)
			worker.Run();
		else
			exit(1);
	}
	else
	{  
		while(1)
		{
			sleep(3);
			
			int status = 0;
			int result = waitpid (pid, &status, WNOHANG);
			if (result != 0 || status != 0)
			{
				LOG (LOG_FATAL, __FILE__, __LINE__, "waitpid(%d, %d)=%d", pid, status, result);
				pid = fork ();
				if(pid == 0)
				{
					mm_framework worker;
					if(worker.Init() == 0)
						worker.Run();
				}
				else if (pid > 0)
				{
					continue;
				}
				else
				{
					printf ("fork error\n");
					return -1;
				}
			}
		}
	}
		
	return 0;

}


